import { RESPONSE_CODE } from "@/common/config";
import { handleRegionList } from "@/common/service";
import {  DataItem, IRegionDataPromie, IRegionResponse, IResponseSuccess } from "@/typing";



const useRegionAction=()=>{
 
    const formatData = (data: any[]): DataItem[] => {
       
        return data.map(item => {
          const children = item.children ? formatData(item.children) : undefined;
          return {
            value: item.code,
            label: item.name,
            children,
          };
        });
      };
    const generateRegionData = (REGION_DATA:any[])=>{

        if(REGION_DATA &&REGION_DATA.length > 0){}
        const regionDataT: DataItem[] = formatData(REGION_DATA);
        // console.log(regionData)
        // code转汉字大对象
        const codeToTextT: { [key: string]: string } = {};
        REGION_DATA.forEach(province => {
            codeToTextT[province.code] = province.name;
          // 将省份的code和name存入codeToText对象中
          province.children.forEach(city => {
          // 遍历城市
          codeToTextT[city.code] = city.name;
            // 将城市的code和name存入codeToText对象中
            if(city.children && city.children.length > 0) {
              city.children.forEach(area => {
                // 遍历区域
                codeToTextT[area.code] = area.name;
                });
            }
            
          });
        });
      
        return {  regionDataT, codeToTextT };
    }
    const handleInitRegionList = async(): Promise<IRegionDataPromie> =>{
        return new Promise(async(resolve,reject)=>{
            const regionRes = await handleRegionList() as IResponseSuccess<IRegionResponse>
            if(regionRes.statusCode ===RESPONSE_CODE.AJAX_SUCCESS && regionRes.data.code === RESPONSE_CODE.SUCCESS){
                const regionDataList = regionRes.data.data;
                // console.log(regionDataList)
                if(regionDataList && regionDataList.length > 0){
                    const {regionDataT, codeToTextT} =generateRegionData(regionDataList)
                    resolve({
                        regionDataT: regionDataT,
                        codeToTextT:codeToTextT
                    })
                }
             
                
    
            }
        })
       
        
    }
    
    return {
       
        handleInitRegionList

    }
    
}
export default useRegionAction;